<?php
declare (strict_types=1);

namespace app\admin\service;

use app\model\system\SystemAdmin;

class LoginService
{
    /**
     * 登录
     * @param $data
     * @return mixed|string
     * @throws \Exception
     * @author dgc<453342213@qq.com>
     * createTime:2020/8/24 11:57
     */
    public function Login($data)
    {
        $where[] = ['username|phone', '=', $data['username']];
        $info = (new SystemAdmin())->getInfo($where, 'id,token,phone,name,head,password,status,salt,group_id');
        //删除之前的缓存
        if (!$info) {
            throw  new \Exception('用户不存在或密码错误', -1);
        }
        if ($info->status != 1) {
            throw  new \Exception('账号已被禁用，如有需要请联系管理员！', -1);
        }
        if ($info->password != setPassword($data['password'], $info->salt)) {
            throw  new \Exception('用户不存在或密码错误', -1);
        }
        $toInfo = $info->toArray();
        unset($toInfo['password']);
        unset($toInfo['token']);
        unset($toInfo['salt']);
        //删除之前的缓存
        redisHdel('admin_user_info', 'admin_' . $info->token);
        $info->token = md5(sha1($info->id . time() . rand(1, 9999)));
        $info->ip = getClientIp();
        $info->save();
        redisHset('admin_user_info', 'admin_' . $info->token, $toInfo);
        return ['token' => $info->token];
    }
}
